package com.demo.common.tool;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;

public class ToolOCR {

	private static final String EOL = System.getProperty("line.separator");
	/**
	 * 文件位置
	 */
	private static String tessPath = new File("tesseract").getAbsolutePath();

	public static String recognizeText(String picUrl) {
		try {
			/**
			 * 设置输出文件的路劲
			 */
			String outputFilePath = tessPath + "\\" + ToolUUID.getUUID();
			StringBuffer strB = new StringBuffer();
			String picPath = tessPath + "\\" + ToolUUID.getUUID() + ".jpg";
			ToolPicture.saveToFile(picUrl, picPath, "jpg");
			StringBuffer sb = new StringBuffer();
			sb.append("\"D:\\Program Files (x86)\\Tesseract-OCR\\tesseract\" \"").append(picPath).append("\" \"").append(outputFilePath).append("\" -l eng");
			Process process = Runtime.getRuntime().exec(sb.toString());
			int w = process.waitFor();
			if (w == 0)// 0代表正常退出
			{
				BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(outputFilePath + ".txt"), "UTF-8"));
				String str;

				while ((str = in.readLine()) != null) {
					strB.append(str).append(EOL);
				}
				in.close();
			} else {
				String msg;
				switch (w) {
				case 1:
					msg = "Errors accessing files. There may be spaces in your image's filename.";
					break;
				case 29:
					msg = "Cannot recognize the image or its selected region.";
					break;
				case 31:
					msg = "Unsupported image format.";
					break;
				default:
					msg = "Errors occurred.";
				}
				throw new RuntimeException(msg);
			}
			new File(outputFilePath + ".txt").delete();
			new File(picPath).delete();
			return strB.toString().replaceAll("\\s*", "");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		long start = System.currentTimeMillis();
		String result = recognizeText(
				"http://www.umetrip.com/mskyweb/graphic.do?str=lf5QSfzpdfe8DopAlvTeow==&width=60&height=25&front=68,68,68&back=248,248,248&size=20&xpos=0&ypos=20");
		System.out.println(result);
		long end = System.currentTimeMillis();
		System.out.println("花费" + (end - start) + "毫秒");
	}
}
